<?php

namespace addons\sum\service\store;

use addons\sum\exception\SumException;
use app\admin\model\sum\store\Apply as ApplyModel;
use app\admin\model\sum\store\Store as StoreModel;
use app\admin\model\sum\user\User;
use think\Db;

class Store
{

    protected $user = null;

    public function __construct($user)
    {
        $this->user = is_numeric($user) ? User::get($user) : $user;
    }

    /**
     * 商户提交审核
     * @param $params
     * @return ApplyModel|array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function apply($params)
    {
        // 查询审核未通过的或者驳回的门店申请信息
        $apply = ApplyModel::where('user_id', $this->user->id)->where('status', 'in', [-1, 0])->find();

        $data['user_id'] = $this->user->id;
        $data['store_name'] = $params['store_name'];
        $data['user_name'] = $params['user_name'];
        $data['agent_id'] = $params['agent_id'];
        $data['phone'] = $params['phone'];
//        $data['image_sfzrx'] = $params['image_sfzrx'];
//        $data['image_sfzgh'] = $params['image_sfzgh'];
        $data['image_business_license'] = $params['image_business_license'];
        $data['status'] = 0;
        if ($apply) {
            $data['apply_num'] = $apply->apply_num + 1;
            $apply->save($data);
        } else {
            $data['apply_num'] = 1;
            $apply = new ApplyModel();
            $apply->save($data);
        }
        Db::name('user')->where('id',$this->user->id)->update(['store_status'=>1]);
        return $apply;
    }

    // 同意
    public function handleAgree($apply, $oper = null)
    {
        if ($apply->status != 0) {
            throw new SumException('请勿重复操作');
        }
        $apply->status = 1;
        $apply->save();

        //自动生成店铺
        $params=[];
        $params['store_name']=$apply['store_name'];
        $params['user_name']=$apply['user_name'];
        $params['phone']=$apply['phone'];
        $params['agent_id']=$apply['agent_id'];
        $params['apply_id']=$apply['id'];
        $params['user_id']=$apply['user_id'];//绑定用户id
        $params['status']='normal';
        $store=new StoreModel();
        $store->save($params);
        Db::name('user')->where('id',$this->user->id)->update(['store_status'=>2,'store_id'=>$store['id']]);
        return $apply;
    }
    // 拒绝
    public function handleRefuse($apply, $refuse_msg)
    {
        if ($apply->status != 0 && $apply->status != 1) {
            throw new SumException('请勿重复操作');
        }
        $apply->status = -1;
        $apply->status_msg = $refuse_msg;
        $apply->save();
        Db::name('user')->where('id',$this->user->id)->update(['store_status'=>-1]);
        return $apply;
    }
}
